/*
 * Ingenic SU SDK PWM test.
 *
 * Copyright (C) 2014 Ingenic Semiconductor Co.,Ltd
 * Author: Tiger <bohu.liang@ingenic.com>
 */

#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>

#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
#include <CUnit/Console.h>
#include <CUnit/Automated.h>

#include <imp/imp_log.h>
#include <imp/imp_common.h>

#include <sysutils/su_pwm.h>

#include <system/system.h>
#include <system/vbm.h>

#define TAG		"TEST_PWM"
#define PERIOD		300000
#define DUTY		100000
#define DUTY_STEP	50000
#define TIMEOUT		20

static void test_pwm()
{
	int ret;
	SUPWMChnAttr attr, attr_bak;

	ret = SU_PWM_Init();
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_CreateChn error !\n");
		CU_FAIL();
		return ;
	}

	attr.period = PERIOD;
	attr.duty = DUTY;
	attr.polarity = 0;

	ret = SU_PWM_CreateChn(0, &attr);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_CreateChn error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_EnableChn(0);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_EnableChn error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_CreateChn(1, &attr);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_CreateChn error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_EnableChn(1);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_EnableChn error !\n");
		CU_FAIL();
		return ;
	}

	sleep(TIMEOUT);

	SU_PWM_DisableChn(0);

	ret = SU_PWM_GetChnAttr(0, &attr_bak);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_GetChnAttr error !\n");
		CU_FAIL();
		return ;
	}

	attr_bak.polarity = 1;

	SU_PWM_DisableChn(1);

	ret = SU_PWM_GetChnAttr(1, &attr_bak);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_GetChnAttr error !\n");
		CU_FAIL();
		return ;
	}

	attr_bak.polarity = 1;

	ret = SU_PWM_SetChnAttr(0, &attr_bak);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_SetChnAttr error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_EnableChn(0);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_EnableChn error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_SetChnAttr(1, &attr_bak);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_SetChnAttr error !\n");
		CU_FAIL();
		return ;
	}

	ret = SU_PWM_EnableChn(1);
	if(ret < 0) {
		IMP_LOG_ERR(TAG, "SU_PWM_EnableChn error !\n");
		CU_FAIL();
		return ;
	}

	sleep(TIMEOUT);

	SU_PWM_DisableChn(0);

	SU_PWM_DestroyChn(0);

	SU_PWM_DisableChn(1);

	SU_PWM_DestroyChn(1);

	SU_PWM_Exit();

	CU_PASS();

	return ;
}

CU_TestInfo PWMTest[] = {
	{"pwm", test_pwm},
	CU_TEST_INFO_NULL,
};
